package com.youzikj.wx.comm.util;

import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;


public class Utils {
	
	private static final String ifNotFromWXThenRedirectURl="http://www.wangcheng.gov.cn";

	/**
	 * 判断字符串是否为null或空字符串
	 * 
	 * @param str
	 * @return
	 */
	public static boolean hasValue(String... str) {
		for (String string : str) {
			if (string == null || "".equals(string))
				return false;
		}
		return true;
	}

	/**
	 * 获取当前时间
	 */
	public static String getCurrentTime(String s) {
		Date date = new Date();
		DateFormat format = new SimpleDateFormat(s);
		return format.format(date);
	}

	
	/**
	 * 获取用户微信openId
	 * @param request
	 * @param response
	 * @return 
	 * @throws Exception
	 */
	public static Map<String, String> getOpenId(HttpServletRequest request) throws Exception {
		String userAgent = request.getHeader("User-Agent");
		Map<String, String> result = new HashMap<String, String>();

	HttpSession session = request.getSession();
		Object openIdO = session.getAttribute("openId");
		if (openIdO != null) {
			result.put("status", "1");
			result.put("openId", openIdO.toString());
			return result;

		} else {
			if (userAgent.indexOf("MicroMessenger") == -1) {
				// 如果不是从微信端登录，则跳转到首页或者关注微信页面。
				result.put("status", "-1");
				result.put("url", ifNotFromWXThenRedirectURl);
				return result;
			}

			// 获取code
			String code = request.getParameter("code");
			String oldUrl = request.getRequestURL().toString();
			if (request.getQueryString() != null)
				oldUrl += "?" + request.getQueryString();

			if (null == code || "".equals(code)) {
				String codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
						+ CommonUtil.appId
						+ "&redirect_uri="
						+ URLEncoder.encode(oldUrl, "utf-8")
						+ "&response_type=code&scope=snsapi_base&state="
						+ URLEncoder.encode(oldUrl, "utf-8")
						+ "#wechat_redirect";
				result.put("status", "0");
				result.put("url", codeUrl);
				return result;
			}

			// 获取微信用户的openId
			String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+ CommonUtil.appId
					+ "&secret="
					+ CommonUtil.appSecret
					+ "&code="
					+ code
					+ "&grant_type=authorization_code";
			System.out.println(("获取OpenID URL:" + tokenUrl));

			 JSONObject httpsRequest = CommonUtil.httpsRequest(tokenUrl, "POST", null);
			System.out.println(("获取OpenID  返回结果：" + httpsRequest.toString()));
			String openId = httpsRequest.getString("openid");
			System.out.println(("获取openId为:" + openId));
			result.put("status", "1");
			result.put("openId", openId);
			result.put("code", code);
	}

		return result;

	}
	 
}
